package plugins.openform;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.events.SetFilterEvent;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.sdk.plugin.Plugin;

import java.util.EventObject;
import java.util.Map;

/**
 * 标准单据列表插件
 */
public class OpenStaffList extends AbstractListPlugin implements Plugin {

    private static final String IDENTITY_PARAM = "Identity";
    private static final String MERCHANT_VALUE = "merchant";
    private static final String MERCHANTDATA = "dcb4_merchantdata";
    private static final String STAFF = "dcb4_staff";
    private static final String MANAGER_NAME = "dcb4_manager_name";
    private static final String AUTHOR_FIELD = "dcb4_author";

    private boolean shouldApplyFilter = false;
    private String currentUser = null;

    private static Object targrtMerchant;

    @Override
    public void afterCreateNewData(EventObject e) {
        // 获取菜单入口参数
        Map<String, Object> customParams = this.getView().getFormShowParameter().getCustomParams();
        String identity = (String) customParams.get(IDENTITY_PARAM);

        if (MERCHANT_VALUE.equals(identity)) {
            // 获取当前用户名
            currentUser = RequestContext.get().getUserName();

            // 检查dcb4_merchantdata中是否存在匹配记录
            QFilter managerFilter = new QFilter(MANAGER_NAME, QCP.equals, currentUser);
            shouldApplyFilter = QueryServiceHelper.exists(MERCHANTDATA, new QFilter[]{managerFilter});

            // 获取商户名
            if (shouldApplyFilter) {
                // 获取商户名
                DynamicObjectCollection merchantData = QueryServiceHelper.query(MERCHANTDATA, "name", new QFilter[]{managerFilter});

                targrtMerchant = merchantData.get(0).getString("name");

                if (merchantData != null && !merchantData.isEmpty()) {
                    String merchantName = merchantData.get(0).getString("name");
                    // this.getView().showTipNotification("当前商户: " + merchantName);
                }
            } else {
                this.getView().showMessage("当前用户没有管理过任何商户！");
            }

            /*
            if (!shouldApplyFilter) {
                this.getView().showMessage("当前用户非商户！");
            }

             */
        }
        super.afterCreateNewData(e);
    }

    @Override
    public void setFilter(SetFilterEvent e) {
        super.setFilter(e);

        // this.getView().showTipNotification("当前用户: " + currentUser);

        if (shouldApplyFilter && currentUser != null) {
            // 添加过滤条件

            // this.getView().showTipNotification("打开员工列表，当前商户: " + targrtMerchant);

            QFilter merchantFilter = new QFilter("dcb4_merchant.name", QCP.equals, targrtMerchant);
            e.addCustomQFilter(merchantFilter);
        }
    }

}